package com.ruoyi.house.service.webmagic;


import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.house.constants.Constants;
import com.ruoyi.house.domain.*;
import com.ruoyi.house.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import us.codecraft.webmagic.selector.Json;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Zln
 * @version 2018-12-28 13:28
 *
 * 饿了么门店信息pipeline
 */

@Component
@Transactional(rollbackFor = Exception.class)
public class BuildingPipeline implements Pipeline{

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private IWebmagicDistrictService districtDao;

    @Resource
    private IWebmagicBuildingService buildingDao;

    @Resource
    private IWebmagicAgencyDataService agencyDataDao;

    @Resource
    private IWebmagicYearService yearSaleDao;

    @Resource
    private IWebmagicBuildingDetailService buildingDetailDao;

    @Resource
    private IWebmagicViewDivService viewDivDao;

    /*@Resource
    private DefaultMQProducer producer;*/

    @SuppressWarnings("unchecked")
    @Override
    public void process(ResultItems rs, Task task) {
        if(rs.get("type") != null) {
            String currentTime = DateUtils.getDate();

            Constants.ProcessType type = rs.get("type");

            switch (type) {
                case BUILDING:

                    // 信息处理
                    List<List<String>> bs = rs.get("buildingList");
                    for (List<String> bds : bs) {
                        logger.info("save building!" + bds);
                        WebmagicBuilding helloBuilding = new WebmagicBuilding();
                        helloBuilding.setProjectName(bds.get(11));
                        helloBuilding.setProjectAddress(bds.get(12));
                        helloBuilding.setDeveloper(bds.get(13));
                        helloBuilding.setDistrict(bds.get(14));
                        helloBuilding.setBuildingName(bds.get(0));
                        helloBuilding.setLicense(bds.get(2));
                        helloBuilding.setBank(bds.get(3));
                        helloBuilding.setBankAccount(bds.get(4));
                        helloBuilding.setHouseNum(Long.valueOf(bds.get(5)));
                        helloBuilding.setHouseArea(Double.valueOf(bds.get(6)));
                        helloBuilding.setForSaleNum(Long.valueOf(bds.get(7)));
                        helloBuilding.setForSaleArea(Double.valueOf(bds.get(8)));
                        helloBuilding.setHasSaleNum(Long.valueOf(bds.get(9)));
                        helloBuilding.setHasSaleArea(Double.valueOf(bds.get(10)));
                        helloBuilding.setDetailUrl(bds.get(1));
                        helloBuilding.setHouseTableUrl(bds.get(15));
                        helloBuilding.setBaseUrl(bds.get(15));
                        helloBuilding.setDate(currentTime);
                        helloBuilding.setBno(helloBuilding.getDetailUrl().split("=")[1]);
                        helloBuilding.setPrjno(helloBuilding.getBaseUrl().split("=")[1]);
                        helloBuilding.setFmid(helloBuilding.getHouseTableUrl().split("=")[1]);
                        buildingDao.insertWebmagicBuilding(helloBuilding);
                    }
                    break;
                case BUILDINGDETAIL:

                    // 信息处理
                    List<List<String>> bsd = (List<List<String>>)rs.get("buildingDetailList");
                    for (List<String> bds : bsd) {
                        logger.info("save buildingdetail!" + bds);
                        WebmagicBuildingDetail buildingDetail = new WebmagicBuildingDetail();
                        buildingDetail.setBuildingType(bds.get(0));
                        buildingDetail.setApproveSaleNum(Long.valueOf(bds.get(1)));
                        buildingDetail.setApproveSaleArea(Double.valueOf(bds.get(2)));
                        buildingDetail.setSaleNum(Long.valueOf(bds.get(3)));
                        buildingDetail.setSaleArea(Double.valueOf(bds.get(4)));
                        buildingDetail.setForSaleNum(Long.valueOf(bds.get(5)));
                        buildingDetail.setForSaleArea(Double.valueOf(bds.get(6)));
                        buildingDetail.setBuildingName(bds.get(7));
                        buildingDetail.setDeveloper(bds.get(8));
                        buildingDetail.setDistrict(bds.get(9));
                        buildingDetail.setDeveloperLevel(bds.get(10));
                        buildingDetail.setBuildingArea(Double.valueOf(bds.get(11)));
                        buildingDetail.setBank(bds.get(12));
                        buildingDetail.setBankAccount(bds.get(13));
                        buildingDetail.setLicense(bds.get(14));
                        buildingDetail.setBaseUrl(bds.get(15));
                        buildingDetail.setDate(currentTime);
                        buildingDetail.setBno(buildingDetail.getBaseUrl().split("=")[1]);
                        buildingDetailDao.insertWebmagicBuildingDetail(buildingDetail);
//                        buildingDao.saveObj(helloBuilding);
                    }
                    break;
                case DISTRICT:
                    // 信息处理
                    List<List<String>> districtList = (List<List<String>>)rs.get("districtList");

                    for (List<String> dt : districtList) {
                        logger.info("save district!" + dt);

                        WebmagicDistrict district = new WebmagicDistrict();
                        district.setProjectName(dt.get(0));
                        district.setUrl(dt.get(1));
                        district.setProjectAddress(dt.get(2));
                        district.setDeveloper(dt.get(3));
                        district.setNoAgency(Long.valueOf(dt.get(4)));
                        district.setSourceUrl(dt.get(5));
                        district.setDate(currentTime);
                        district.setPrjno(district.getUrl().split("=")[1]);
                        String str = JSON.toJSONString(district);
                        //发送mq消息
                        /*Message msg;
                        try {
                            msg = new Message("test-demo"
                                    , "111"
                                    , UUID.randomUUID().toString()
                                    , str.getBytes("utf-8"));
                            SendResult result = producer.send(msg);
                            if (result.getSendStatus() == SendStatus.SEND_OK) {
                                System.out.println("消息发送成功");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }*/
                        int res = districtDao.insertWebmagicDistrict(district);
                    }
                    break;
                case YEARSALE:
                    // 信息处理
                    List<List<String>> yearDataList = (List<List<String>>)rs.get("yearDataList");

                    for (List<String> dt : yearDataList) {
                        logger.info("save yearData:" + dt);
                        WebmagicYear yearSale = new WebmagicYear();
                        yearSale.setDistrict(dt.get(0));
                        yearSale.setSaleNum(Long.valueOf(dt.get(1)));
                        yearSale.setBuildSaleNum(Long.valueOf(dt.get(2)));
                        yearSale.setAgencyNum(Long.valueOf(dt.get(3)));
                        yearSale.setAgencyArea(Double.valueOf(dt.get(4)));
                        yearSale.setDate(currentTime);

                        int res = yearSaleDao.insertWebmagicYear(yearSale);
                    }
                    break;
                case AGENCY:
                    // 信息处理
                    List<String> agencyList = (List<String>)rs.get("agency");
                    agencyList = agencyList.subList(4,agencyList.size()-1);
                    int count = 1;
                    WebmagicAgencyData agencyData = new WebmagicAgencyData();
                    for (String dt : agencyList) {
                        logger.info("save agency:" + dt);
                        if (count%3 == 1){
                            agencyData.setUsaged(dt);
                        }else if (count%3 == 2){
                            agencyData.setAgencyNum(Long.valueOf(dt));
                        }else if (count%3 == 0){
                            agencyData.setAgencyArea(Double.valueOf(dt));
                            logger.info("agency:{}",agencyData);
                            agencyData.setDate(currentTime);
                            agencyDataDao.insertWebmagicAgencyData(agencyData);
                        }
                        count++;
                    }
                    break;
                case VIEWDIV:
                    Json view = rs.get("viewDiv");
                    String downUrl = rs.get("viewDivUrl");
                    String sourceUrl = rs.get("sourceUrl");
                    try {
                        WebmagicViewDiv viewDiv = view.toObject(WebmagicViewDiv.class);
                        viewDiv.setDownUrl(downUrl);
                        viewDiv.setSourceUrl(sourceUrl);
                        viewDiv.setFmid(sourceUrl.split("=")[1]);
//                        logger.info("viewDiv:{}",viewDiv);
                        viewDiv.setDate(currentTime);
                        viewDivDao.insertWebmagicViewDiv(viewDiv);
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.info("--------downUrl:{}",downUrl);
                    }
                    break;
                default:
                    logger.error("未知处理类型！");
                    break;
            }
        }
        else {
            // 未抓取到信息
            logger.error("未抓取到需要处理的信息！");
        }
    }

}
